<?php
namespace app\common\repositories\system;
use app\common\repositories\BaseRepository;
use app\common\dao\system\CategoryDao as dao;
use app\common\repositories\work\WorkTypeRepository;
use basic\traits\CategoresRepository;
use FormBuilder\Factory\Elm;
use think\facade\Cache;
use think\facade\Route;

/**
 * @mixin dao
 */
class CategoryRepository extends BaseRepository
{
    use CategoresRepository;

    const TYPE_MAP = [
        'find_work'=>'工地找活',
        'find_man' => '工地招工',
        'work_type'=>'工种',
        'union_business'=>'行业',
       // 'union_identity'=>'行业',
        'course_category'=>'课程',
    ];

    const TYPE_MAX_LEVEL = [
        'find_work'=>1,
        'find_man' => 1,
        'work_type'=>3,
        'union_business'=>2,
        'union_identity'=>3,
        'course_category'=>1,
    ];


    protected $cacheKey = 'category_list_7';

    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }

    public function getApiList($type)
    {
        if(!$data = $this->getCache($type)){
            $data = $this->getApiFormatList($type,1);

            if(in_array($type,['find_work','find_man'])){
                foreach ($data as $k=>$v){
                    $data[$k]['work_type'] = app()->make(WorkTypeRepository::class)->getWorkTypeDataById($v['category_id']);
                }
            }else if($type == 'union_business'){
                foreach ($data as $k=>$v){
                    $data[$k]['identity'] = $this->getApiFormatList('union_identity_'.$v['category_id'],1);
                }
            }
            $this->setCache($type,$data);
        }

        $hasAll = input('has_all',0) == 1;
        return $hasAll ? $this->setApiData($data):$data;
    }



    public function setApiData($data,$categoryId = '',$pid = '')
    {

        if(count($data)) array_unshift($data,['category_id'=>$categoryId,'cate_name'=>'全部','pid'=>$pid,'children'=>[]]);

        foreach ($data as $key=>$item){

            if(isset($item['type']) && $item['type'] == 'union_business' && isset($item['identity'])){
                $data[$key]['identity'] = $this->setApiData($item['identity']);
            }


            if(isset($item['children']) && count($item['children'])){
                $data[$key]['children'] = $this->setApiData($item['children'],$item['category_id'],$item['pid']);
            }
        }
        return $data;
    }


    public function getCache($type)
    {
        $key = $this->cacheKey.$type;
        if(!Cache::has($key)) return null;

        return json_decode(Cache::get($key),true);
    }


    public function setCache($type,$data)
    {
        $key = $this->cacheKey.$type;
        Cache::set($key,json_encode($data),60*60*2);
    }


    public function delCache($type)
    {
        $key = $this->cacheKey.$type;
        if(Cache::has($key)) Cache::delete($key);
        if($type == 'work_type'){
            Cache::delete($this->cacheKey.'find_work');
            Cache::delete($this->cacheKey.'find_man');
        }

        if(substr($type,0,14) === 'union_identity'){
            Cache::delete($this->cacheKey.'union_business');
        }
    }


    public function form(String $type, ?int $id = null, array $formData = [])
    {
        $form = Elm::createForm(is_null($id) ? Route::buildUrl('systemCategoryCreate')->build() : Route::buildUrl('systemCategoryUpdate', ['id' => $id])->build());

        $form->setRule([
            Elm::input('max_level','当前分类最大层级',$this->dao->getMaxLevel($type).'级')->disabled(true),
            Elm::cascader('pid', '上级分类')->options(function () use ($id, $type) {
                $menus = $this->dao->getAllData($type,1,$this->dao->getMaxLevel($type)-1);
                if ($id && isset($menus[$id])) unset($menus[$id]);
                $menus = formatCascaderData($menus, 'cate_name');
                array_unshift($menus, ['label' => '顶级分类', 'value' => 0]);
                return $menus;
            })->props(['props' => ['checkStrictly' => true, 'emitPath' => false]])->filterable(true)->appendValidate(Elm::validateInt()->required()->message('请选择上级分类')),
            Elm::input('cate_name', '分类名称')->required(),
            Elm::uploadImage('pic', '分类图片(110*110px)', config('app.site_url').Route::buildUrl('systemUploadFile', ['field' => 'file'])->suffix('')->build())->headers(['X-Token' => request()->token()]),
           // Elm::frameImage('pic', '分类图片(110*110px)', '/' . config('admin.admin_prefix') . '/setting/uploadPicture?field=pic&type=1')->width('896px')->height('480px')->props(['footer' => false])->modal(['modal' => false, 'custom-class' => 'suibian-modal']),
            Elm::switches('is_show', '是否显示', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启'),
            Elm::number('sort', '排序', 0),
            Elm::hidden('type',$type),
        ]);

        $typeName = self::TYPE_MAP[$type]??'';
        return $form->setTitle(is_null($id) ? "添加{$typeName}分类" : "编辑{$typeName}分类")->formData($formData);
    }

    public function updateForm($type, $id)
    {
        return $this->form($type, $id, $this->dao->get($id)->toArray());
    }


    public function getFormatList($type, $status = null)
    {
        return formatCategory($this->dao->getAll($type,$status,['path'])->toArray(), $this->dao->getPk());
    }

    public function getApiFormatList($type, $status = null)
    {
        return formatCategory($this->dao->getAll($type,$status,['path','level','create_time'])->toArray(), $this->dao->getPk());
    }


    public function getTreeList($type)
    {
        $menus = $this->dao->getAllData($type);
        return formatCascaderData($menus,'cate_name');
    }


    public function getList($type)
    {
        $menus = $this->dao->getAllData($type);
        $menus = formatCascaderData($menus, 'cate_name', 3);
        return $menus;
    }

    /**
     * 检测是否超过最低等级限制
     * @param int $id
     * @param string $type
     * @param int $level
     * @return bool
     */
    public function checkLevel(int $id,string $type,int $level = 0)
    {
        $check = $this->getLevelById($id);
        if($level)
            $check = $level;
        return $check < $this->dao->getMaxLevel($type);
    }


    public function allChildrenDetail($id): array
    {
        $data = $this->getAllShowChildren($id);
        return formatCategory($data,'category_id','pid','children',$id);
    }

    public function exists($type,$id)
    {
        return $this->dao->fieldExistsList($type,'category_id',$id);
    }
}